package cn.dujc.superkid.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;

import cn.dujc.core.ui.BaseActivity;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.adapter.UnitTestAdapter;
import cn.dujc.superkid.adapter.UnitTestMsgAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.ExaminePageResult;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.bean.UnitResult;
import cn.dujc.superkid.bean.UnitTestResult;
import cn.dujc.superkid.bean.VideoExaminationResult;
import cn.dujc.superkid.bean.VideoExaminationResultsResult;
import cn.dujc.superkid.utils.KeyboardChangeListener;
import cn.dujc.superkid.utils.Preferences;
import cn.dujc.superkid.utils.SoftKeyBoardListener;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/10/15 0015.
 */

public class UnitTestActivity extends BaseActivity implements UnitTestAdapter.OnItemViewClickListener, View.OnClickListener, TextWatcher, KeyboardChangeListener.KeyBoardListener {
    private Chronometer chronometer;
    private String examine_id;
    private RecyclerView testRecycler;
    private RecyclerView msgRecycler;
    private UnitTestAdapter testAdapter;
    private UnitTestMsgAdapter msgAdapter;
    private View liuyan_group;
    private EditText liuyan_edit;
    private TextView liuyan_submit;
    private View addLiuyan;
    private TextView btmTitle;
    private View submitView;

    @Override
    public int getViewId() {
        return R.layout.activity_unittest;
    }


    @Override
    public void initBasic(Bundle savedInstanceState) {
        new KeyboardChangeListener(this).setKeyBoardListener(this);
        examine_id = getIntent().getStringExtra("examine_id");
        setTitle("考试");
        initView();
        loadData(0);
    }

    private void initView() {
        submitView = findViewById(R.id.bt_tijiao);
        submitView.setOnClickListener(this);
        btmTitle = findViewById(R.id.tv_title);
        liuyan_group = findViewById(R.id.liuyan_group);
        addLiuyan = findViewById(R.id.l_liuyan);
        liuyan_submit = findViewById(R.id.liuyan_submit);
        liuyan_submit.setOnClickListener(this);
        addLiuyan.setOnClickListener(this);
        liuyan_edit = findViewById(R.id.liuyan_edit);
        liuyan_edit.addTextChangedListener(this);
        chronometer = findViewById(R.id.chronometer);
        chronometer = findViewById(R.id.chronometer);
        chronometer.setBase(SystemClock.elapsedRealtime());//计时器清零
        int hour = (int) ((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000 / 60);
        chronometer.setFormat("0" + String.valueOf(hour) + ":%s");
        testRecycler = findViewById(R.id.unit_test_recycler);
        testRecycler.setNestedScrollingEnabled(false);
        testRecycler.setLayoutManager(new LinearLayoutManager(this));
        testAdapter = new UnitTestAdapter(this);
        testAdapter.setOnItemViewClickListener(this);
        testRecycler.setAdapter(testAdapter);
        msgRecycler = findViewById(R.id.unit_test_mes_recycler);
        msgRecycler.setNestedScrollingEnabled(false);
        msgRecycler.setLayoutManager(new LinearLayoutManager(this));
        msgAdapter = new UnitTestMsgAdapter(this);
        msgRecycler.setAdapter(msgAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * @param type type =1时   试题数据不变
     */
    private void loadData(final int type) {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(this);
        HttpHelper.getExamineOnline().videoExamination(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(this).getChannel_id())
                .put("logincode", loginResult.getLogincode())
                .put("examination_id", examine_id)//试卷id
                .create()).enqueue(new Callback<Result<UnitTestResult.DataBean>>() {
            @Override
            public void onResponse(Call<Result<UnitTestResult.DataBean>> call, Response<Result<UnitTestResult.DataBean>> response) {
                if (type != 1) {//type =1时刷新页面数据   type=0时  只刷新留言数据
                    testAdapter.setList(response.body().getData().getExamination_list());
                    btmTitle.setText("共有" + testAdapter.getList().size() + "道题目，考试时间为90分钟，共计100分");
                }
                msgAdapter.setDatas(response.body().getData().getMessage_list());
                chronometer.start();
            }

            @Override
            public void onFailure(Call<Result<UnitTestResult.DataBean>> call, Throwable t) {

            }
        });
    }

    @Override
    public void onItemViewClick(View v, int pos) {
        if (v.getId() == R.id.exercises_jiexi) {
            Intent intent = new Intent(this, AnalysisActivity.class);
            intent.putExtra("title", testAdapter.getList().get(pos).getProblem_title());
            intent.putExtra("content", testAdapter.getList().get(pos).getExplain());
            startActivity(intent);
        } else {
            addGoodQuestion(pos);
        }
    }

    //加入到好题本
    public void addGoodQuestion(int pos) {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getCourse().videoGoodQuestion(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("exercises_id", testAdapter.getList().get(pos).getId())
                .put("logincode", loginResult.getLogincode())
                .put("type_id", 1)
                .create()).enqueue(new ResultCallBack<Result<Object>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                ToastUtil.showToast(mActivity, body.getMsg());
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                if(code==400){
                    ToastUtil.showToast(mActivity, msg);
                }else{
                    ToastUtil.showToast(mActivity, "未能读取数据，因为它的格式不正确");
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == addLiuyan) {
            Intent intent =new Intent(this,LeavingActivity.class);
            intent.putExtra("examine_id",examine_id+"");
            intent.putExtra("type","1");
            startActivityForResult(intent,1);
        } else if (v == liuyan_submit) {
            if (liuyan_edit.getText().length() > 0) {
                submitMessage();
            }
        } else if (v == submitView) {
            submitTest();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1&&resultCode==RESULT_OK){
            loadData(1);
        }
    }

    private void submitMessage() {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getCourse().message(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("examine_id", Integer.parseInt(examine_id))
                .put("logincode", loginResult.getLogincode())
                .put("type_id", 1)
                .put("content", liuyan_edit.getText().toString())
                .create()).enqueue(new ResultCallBack<Result<Object>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                hideKeyboard();
                liuyan_group.setVisibility(View.GONE);
                liuyan_edit.setText("");
                ToastUtil.showToast(mActivity, body.getMsg());
                loadData(1);
            }
        });
    }

    //强制隐藏键盘
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(liuyan_edit.getWindowToken(), 0);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 0) {
            liuyan_submit.setTextColor(Color.parseColor("#888888"));
        } else {
            liuyan_submit.setTextColor(Color.parseColor("#222222"));
        }
    }

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        Log.d("onKeyboardChange", "onKeyboardChange() called with: " + "isShow = [" + isShow + "], keyboardHeight = [" + keyboardHeight + "]");
        ToastUtil.showToast(mActivity, isShow + "");
    }

    private void submitTest() {
        for (int i = 0; i < testAdapter.getList().size(); i++) { //校验是否有题没填写答案
            if (TextUtils.isEmpty(testAdapter.getList().get(i).getValue())) {
                ToastUtil.showToast(this, "第" + (i + 1) + "题没答");
                return;
            }
        }
        requestSubmit();
    }




    private void requestSubmit() {
        Log.e("submit", testAdapter.getValue());
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        QMap map = QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("examine_id", Integer.parseInt(examine_id))
                .put("logincode", loginResult.getLogincode())
                .put("answer", testAdapter.getValue())
                .put("when", chronometer.getText())
                .create();
        Log.e("qmap", new Gson().toJson(map));
        HttpHelper.getCourse().videoExaminationResults(map).enqueue(new ResultCallBack<Result<UnitResult.DataBean>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<UnitResult.DataBean> body) {
                ArrayList<UnitResult.DataBean.ResultsBean>list= (ArrayList<UnitResult.DataBean.ResultsBean>) body.getData().getResults();
                ArrayList<UnitResult.DataBean.ScoreStatisticsBean>list1= (ArrayList<UnitResult.DataBean.ScoreStatisticsBean>) body.getData().getScore_statistics();
                ArrayList<UnitTestResult.DataBean.ExaminationListBean>testList= (ArrayList<UnitTestResult.DataBean.ExaminationListBean>) testAdapter.getList();
                starter().with("unitResult", list)
                        .with("num",body.getData().getPage_info().getNum())
                        .with("first_score",body.getData().getPage_info().getFirst_score()+"")
                        .with("total_score",body.getData().getPage_info().getTotal_score()+"")
                        .with("title",body.getData().getPage_info().getExamine_title())
                        .with("statistics",list1)
                        .with("testList",testList)
                        .go(UnitTestResultActivity.class);
                finish();
            }
        });
    }
}
